<?php

class AlbumsController extends AppController {
  //public $scaffold;
  public $helpers = array('Html', 'TWSForm', 'Paginator');
  public $components = array('Session','Util');
  public $name = 'Albums';
  public $paginate;

  function __construct($request=null, $response=null) {
    parent::__construct($request, $response);
    $this->paginate = array(
        'limit' => Configure::read('App.pageResultLimit'),
        'order' => array(
            'Album.name' => 'asc'
            ));
  }

  function admin_main() {$this->layout = "admin";}

  function index($categoryId) {
    if (empty($categoryId)) {
      throw new NotFoundException();
    } else {
      //get albums in this category
      $this->set('title_for_layout','Allied Caterers Photo Album');
      $this->set("meta_keywords","Photos Albums Images Gallery Pics Pictures Allied Caterers, Trinidad and Tobago");
      $this->set("meta_description","Album photos for Allied Caterers.");
      $this->loadModel('Category');
      $categoryInfo = $this->Album->Category->find('first',array('conditions'=>array('Category.id'=>$categoryId), 'fields'=>array('Category.id', 'Category.name')));
      if (empty($categoryInfo)) {
        $this->redirect('/image-gallery', true);
      }
      $this->set(array('categoryInfo' => $categoryInfo));

      $validAlbums = $this->Category->Album->query('Select Album.id from albums as Album, photos as Photo where Album.id=Photo.album_id and Album.category_id=\''.$categoryId.'\' group by Album.id having Count(Photo.id)>0');
      $validAlbumArray = array();
      foreach($validAlbums as $album) {
        array_push($validAlbumArray, $album['Album']['id']);
      }

      $this->paginate = array(
          'Photo'=>array(
            'order' =>array('Photo.image_order') //Does not work here -- This was done in main model
          ),
          'Album'=>array(
          'limit' => Configure::read('App.albumDisplayLimit'),
          'order' => array(
              'Album.created' => 'desc'
            ),
            'conditions'=> array('Album.category_id'=>$categoryId, 'Album.id'=>$validAlbumArray)
              )
          );
      

      //$result = $this->paginate($this->Album, array('Album.category_id'=>$categoryId,'Album.id'=>$validAlbumArray));
      $result = $this->paginate($this->Album);
      $this->set('albumResults', $result);
      
      //http://bakery.cakephp.org/articles/shird10/2010/08/29/pagination-for-custom-queries
      //$db =ConnectionManager::getDataSource('default');
      //debug($db->showLog());

    }
  }

  function getRotatingPhotos(){
    $rotatingPhotos = $this->Session->read('RotatingPhotos');
    if(empty($rotatingPhotos)){
      $adminAlbums = Configure::read('App.administrativeAlbums');
      $rotatingPhotos = $this->getAlbumPhotos($adminAlbums['Rotating Images']['id']);
      $this->Session->write('RotatingPhotos', $rotatingPhotos);
    }
    return $rotatingPhotos;
  }

  function getAlbumPhotos($albumId){
    $this->loadModel('Photo');
    $retVal = null;
    if(!empty($albumId)){
      $photos = $this->Photo->find("all",array("conditions"=>array("Photo.album_id"=>$albumId),"order"=>array("Photo.image_order")));
      if (!empty($photos)) {
        $retVal = array();
        foreach ($photos as $photo) {
          if(!empty($photo['Photo'])){
          array_push($retVal, $photo['Photo']);
          }
        }
      }
    }
    return $retVal;
  }

//admin and public version
  function admin_index($categoryId=null) {
    $this->layout = "admin";
    if(!empty($categoryId)) {
     $categoryInfo = $this->Album->Category->find('first',array('conditions'=>array('Category.id'=>$categoryId), 'fields'=>array('Category.id', 'Category.name')));
      if (empty($categoryInfo)) {
        $this->redirect('index');
      }
      $this->set(array('categoryInfo' => $categoryInfo));
      $this->set('albums', $this->paginate('Album',array('Album.category_id' => $categoryId)));
    } else {
      $this->set('albums', $this->paginate('Album'));
    }
  }
  //http://book.cakephp.org/1.3/view/1047/Joining-tables

  //admin
  function admin_add($categoryId=null) {
    $this->layout = "admin";
    if(!empty($categoryId)) {
     $categoryInfo = $this->Album->find('first',array('conditions'=>array('Category.id'=>$categoryId), 'fields'=>array('Category.id', 'Category.name')));
     $this->set(array('categoryInfo' => $categoryInfo));
    }
    $this->set('options', $this->Album->Category->find('list', array('fields'=> array('Category.id','Category.name'), 'conditions'=>array('Category.id !='=>Configure::read('App.administrativeCategory')),  'order'=>array('name'=>'asc')  )));
    if ($this->request->is('post')) {
      $this->_processAction($this->request, 'add');
    } 
  }

  //admin
  function admin_edit($id = null) {
    $this->layout = "admin";
    $this->Album->id = $id;
    $this->set('options', $this->Album->Category->find('list', array('fields'=> array('Category.id','Category.name'),  'conditions'=>array('Category.id !='=>Configure::read('App.administrativeCategory')), 'order'=>array('name'=>'asc')  )));
    if ($this->request->is('get')) {
      $this->request->data = $this->Album->read();
      if(empty($this->request->data)) {
        throw new NotFoundException();
      }
    } else {
      //check for delete announcement
      if (isset($this->request->data['deleteBtn'])) {
        $this->member_delete($id);
      } else {
        $this->_processAction($this->request, 'edit', $id);
      }
    }
  }

  private function _processAction($dataIn, $action='add', $id=null) {
      $data = $this->_processRequestData($dataIn);
      $this->Album->set($data);
      if ($this->Album->validates()) {
        if ($this->Album->save($data, false)) {
          $this->Session->setFlash('The record was successfully saved.');
          $this->redirect(array('action' => 'index'));
        }
      } else {
        if($action!=='add') {
          $data['Album']['id']=$id;
        }
        $this->request->data['Album'] = $data['Album'];
        $this->set('errors', $this->Album->validationErrors);
      }
      if($action==='add') {
        $this->render('member_add');
      } else {
        $this->render('member_edit');
      }
  }
  
  function admin_delete($id) {
    $this->layout = "admin";
    $albumPhotos = $this->Album->Photo->find("all", array("conditions"=>array("Album.id"=>$id)));
    if ($this->Album->delete($id, true)) {
      //Clean Up - We do not care if an error occurs while image clean up happens
      //delete photos
      $this->Album->Photo->deleteAll(array('Photo.album_id' => $id));
      //delete physical files
      if (!empty($albumPhotos)) {
        foreach ($albumPhotos as $albumPhoto) {
          $photo = $albumPhoto['Photo'];
          if (!empty($photo)) {
            $imagePath = $photo['image_path'];
            $imageThumbPath = $photo['image_thumb_path'];
            if (!empty($imagePath)) {
              $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imagePath);
            }
            if (!empty($imageThumbPath)) {
              $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imageThumbPath);
            }
          }
        }
      }
      $this->Session->setFlash('The record has been deleted.');
      $this->redirect(array('action' => 'index'));
    }
  }

}

?>
